package homework.valid.validators.impl;

import homework.util.db.DBEngine;
import homework.valid.validators.BaseValidator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class InDBValidator extends BaseValidator {

    private String dbField;
    private String dbTable;
    private DBEngine engine;

    public InDBValidator(String msg, DBEngine eng, String table, String field) {
        // FIXME: 验证table和filed防止注入
        super(msg);
        engine = eng;
        dbField = field;
        dbTable = table;
    }

    @Override
    public boolean isValid(Object v) {
        int count;
        try {
            String sql = "SELECT COUNT(%s) FROM %s WHERE %s = ?";
            sql = String.format(sql, dbField, dbTable, dbField);
            Connection conn = engine.getConnection();
            PreparedStatement sm = conn.prepareStatement(sql);
            sm.setString(1, (String)v);
            ResultSet result = sm.executeQuery();
            count = result.getInt(1);

            DBEngine.close(conn, sm, result);
        } catch (SQLException e) {
            e.printStackTrace();
            return true;
        }
        return count > 0;
    }
}
